<template>
  <div class="download_zip">
    <template>
      <el-button type="primary" v-bind="$attrs" @click="downloadAll">{{$attrs.buttonText || '一键下载'}}</el-button>
    </template>
  </div>
</template>

<script>

import { AjaxUtil } from "base/lib";
export default {
  name: 'downloadZip',
  mixins: [],
  components: {},
  props: {
    value:{},
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    downloadList: {
      type: Array,
      default: () => []
    },
    zipName: {
      type: String,
      default: '公文'
    }
  },
  data() {
    return {
      
    }
  },
  watch: {},
  created() {},
  mounted() {
  },
  methods: {
    async downloadAll() {
      if (!Array.isArray(this.downloadList) || !this.downloadList.length) {
        this.$message.warning('请配置正确的id集合')
      // } else if (this.downloadList.length === 1) {
      //   // window.open(`/XFfileServer/fileDownload?id=${this.downloadList[0]}`,"_self")
      } else {
        // 引入jszip库
        const JSZip = require('jszip');
        // 创建一个新的ZIP压缩包
        const zip = new JSZip();
        for(let item of this.downloadList) {
          const file = await this.downloadById(item)
          zip.file(file.fileName, file.blob);
        }
        zip.generateAsync({ type: 'blob' })
          .then((blob) => {
            // 压缩包生成成功
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${this.zipName}.zip`;
            a.click();
            window.URL.revokeObjectURL(url);
          })
          .catch(function (error) {
            console.error('生成压缩包时发生错误：', error);
          });
      }
    },
    async downloadById(id) {
      const resp = await AjaxUtil
      .ajax({
        responseType : 'blob',
        url: `/XFfileServer/fileDownload?id=${id}`,
        method: 'GET',
        data: {},
      })
      let fileName = resp.headers['content-disposition']
      // 1===字符串
      const index = fileName.indexOf('filename=') + 9 + 1
      fileName = fileName.slice(index, fileName.length -1)
      fileName = decodeURIComponent(fileName)
      const blob = new Blob([resp.data], {
        type: 'application/json,charset=utf-8'
      })
      return {
        fileName,
        blob
      }
    }
  },
};
</script>
<style lang="scss" scoped>
.demo {
  width: 100%;
}
</style>